from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.template.loader import get_template
from django.shortcuts import render
from django.template import RequestContext, loader
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
import json
from storagedata import models
from san.models import Storage,Wwn,San,Doment
import logging
# Create your views here.
import threading


@login_required(login_url="/login/")
def Storagemessages(request,storage_id):
    obj = Storage.objects.get(id = storage_id)
    map = models.STMAP.objects.filter(storage_id=storage_id)
    host = models.STHOST.objects.filter(storage_id=storage_id)
    hostgroup = models.STHOSTgroup.objects.filter(storage_id=storage_id)
    lun = models.STLUN.objects.filter(storage_id=storage_id)
    lungroup = models.STLUNgroup.objects.filter(storage_id=storage_id)
    port = models.STPORT.objects.filter(storage_id=storage_id)
    portgroup = models.STPORTgroup.objects.filter(storage_id=storage_id)
    disk = models.DISK.objects.filter(storage_id=storage_id)
    raidgroup = models.RAIDgroup.objects.filter(storage_id=storage_id)
    from work.models import Work
    work = Work.objects.filter(WO_storage = storage_id)
    data ={
        "map":map,
        "host":host,
        "hostgroup":hostgroup,
        "lun":lun,
        "lungroup":lungroup,
        "port":port,
        "portgroup":portgroup,
        "storage":obj,
        "work":work,
        "disk":disk,
        "raidgroup":raidgroup
    }
    if obj.ST_prodname == "富士通":
        return render(request, "storagemess.html", data)
    elif obj.ST_prodname == "日立":
        return render(request, "storage_rili.html", data)
    elif obj.ST_prodname == "华为":
        return render(request,"storagemess.html",data)

@login_required(login_url="/login/")
def Storage_one_update_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        iddict = request.POST
        id = iddict["id"]
        objst = Storage.objects.filter(id = id).first()
        st_log =Doment.objects.filter(storage_id=objst.id).order_by("-dotime").first()
        if st_log:
            if objst.ST_prodname == "富士通":
                if st_log:
                    from storagedata.fsttodata import Fsttodata
                    t1 = threading.Thread(target=Fsttodata,args=(id,st_log.text,))
                    t1.start()
                else:
                    ret["status"] = False
                    ret["error"] = "该存储没有日志"
            elif objst.ST_prodname == "日立":
                from storagedata.hitachiscript import hitachi_to_data
                if st_log:
                    # hitachi_to_data(id,st_log.text)
                    t2 = threading.Thread(target=hitachi_to_data,args=(id,st_log.text,))
                    t2.start()
                else:
                    ret["status"] = False
                    ret["error"] = "该存储没有日志"
            elif objst.ST_prodname == "华为":
                if st_log:
                    from storagedata.huweiscript import Huaweitodata
                    # Huaweitodata(id,st_log.text)
                    t3 = threading.Thread(target=Huaweitodata,args=(id,st_log.text,))
                    t3.start()
                else:
                    ret["status"] = False
                    ret["error"] = "该存储没有日志"
            objst.ST_updatetime = st_log.dotime
            objst.save()
        else:
            ret["status"] = False
            ret["error"] = "该存储没有日志或者功能还未开发"
    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def Storage_one_delete_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        iddict = request.POST
        id = iddict["id"]
        st_log = models.STMAP.objects.filter(storage_id=id)
        if st_log:
            try:
                models.STMAP.objects.filter(storage_id=id).delete()
                models.STHOST.objects.filter(storage_id=id).delete()
                models.STHOSTgroup.objects.filter(storage_id=id).delete()
                models.STLUN.objects.filter(storage_id=id).delete()
                models.STLUNgroup.objects.filter(storage_id=id).delete()
                models.STPORT.objects.filter(storage_id=id).delete()
                models.STPORTgroup.objects.filter(storage_id=id).delete()
            except Exception as e:
                ret["status"] = False
                ret["error"] = "清除失败%s"%(e)
        else:
            ret["status"] = False
            ret["error"] = "该存储没有日志"

    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def Storage_update_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        try:
            objst = Storage.objects.all()
            for i in objst:
                st_log = Doment.objects.filter(storage_id=i.id).order_by("-dotime").first()
                if st_log:
                    if i.ST_prodname == "富士通":
                        if st_log:
                            from storagedata.fsttodata import Fsttodata
                            t1 = threading.Thread(target=Fsttodata, args=(i.id, st_log.text,))
                            t1.start()
                    elif i.ST_prodname == "日立":
                        from storagedata.hitachiscript import hitachi_to_data
                        if st_log:
                            t2 = threading.Thread(target=hitachi_to_data, args=(i.id, st_log.text,))
                            t2.start()
                    elif i.ST_prodname == "华为":
                        if st_log:
                            from storagedata.huweiscript import Huaweitodata
                            t3 = threading.Thread(target=Huaweitodata, args=(i.id, st_log.text,))
                            t3.start()
                    i.ST_updatetime = st_log.dotime
                    i.save()
        except Exception as e:
            ret["status"] = False
            ret["error"] = "未知错误%s"%(e)
    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def Storage_app_modfiy(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        iddict = request.POST
        id = iddict["id"]
        text = iddict["text"]
        print(text)
        try:
            obj = models.STMAP.objects.get(id = int(id))
            obj.app = text
            obj.save()
        except Exception as e:
            ret["status"] = False
            ret["error"] = "未知错误%s"%(e)
    return HttpResponse(json.dumps(ret))
@login_required(login_url="/login/")
def Storage_num_update_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        # from storagedata.storage_num import FST_lunnum,rili_lunnum
        # try:
        #     obj = Storage.objects.all()
        #     for i in obj:
        #         if i.ST_prodname == "富士通":
        #             s1 = threading.Thread(target=FST_lunnum,args=(i.id,))
        #             s1.start()
        #             # FST_lunnum(i.id)
        #         elif i.ST_prodname == "日立":
        #             s2 = threading.Thread(target=rili_lunnum,args=(i.id,))
        #             s2.start()
        #             # rili_lunnum(i.id)
        #         elif i.ST_prodname == "华为":
        #             s3 = threading.Thread(target=FST_lunnum,args=(i.id,))
        #             s3.start()
        #             # FST_lunnum(i.id)
        # except Exception as e:
        #     ret["status"] = False
        #     ret["error"] = "未知错误%s"%(e)
        from storagedata.storage_num import sumcmount
        t1 = threading.Thread(target=sumcmount)
        t1.start()
    return HttpResponse(json.dumps(ret))

@login_required(login_url="/login/")
def Storagetables(request):
    ret = {}
    obj = Storage.objects.all()
    ret["data"] = obj
    name = []
    for i in obj:
        name.append(i.ST_prodect)
    ret["name"] = json.dumps(name)
    na = {
        "type": 'category',
        "data": name
    }
    ret["na"] = json.dumps(na)
    return render(request,"storagetable.html",ret)
@login_required(login_url="/login/")
def Storagetable_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    obj = Storage.objects.all()
    name = []
    toalnum = []
    for i in obj:
        name.append(i.ST_prodect)
        toalnum.append(i.ST_totalrawcap)
    ret["storagename"] = name
    ret["toalnum"] = toalnum
    ret["totnum"] = {"name":"裸容量","type":'bar',"data":toalnum}
    return HttpResponse(json.dumps(ret))


def storage_stmap_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        obj = models.STMAP.objects.filter(storage_id= id)
        html = ""
        for i in obj:
            groupname = ""
            for z in i.manyportgroup.all():
                groupname += str( z.portgroupname)
            hostpname = ""
            for z in i.manyhostgroup.all():
                hostpname += str( z.hostgroupname)
            lungroupname = ""
            for z in i.manylungroup.all():
                lungroupname += str( z.lungroupname)
            html += "<tr>"+ "<td>" + str(i.id) +"</td>" + \
                    "<td>" + str( i.app) +"</td>" + \
                    "<td>" + groupname  +"</td>" + \
                    "<td>" + hostpname +"</td>" + \
                    "<td>" + lungroupname +"</td>"+ \
                    "<td>" + str(i.totalcap) +"</td>" + "</tr>"
        ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def stroage_mess_host_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        obj = models.STHOST.objects.filter(storage_id=id)
        html =""
        for i in obj:
            hostgoupname = ""
            for k in i.sthostgroup_set.all():
                hostgoupname += str(k.hostgroupname)
            wwn = ""
            sanwwn = ""
            rx = ""
            tx =""
            host = ""
            hostapp = ""
            for k in i.wwn_set.all():
                wwn += str(k.wwn) + "<br> "
                if k.Sanport_wwn:
                    sanwwn += str(k.Sanport_wwn.san) + " " + str(k.Sanport_wwn.slot) + "-" + str(k.Sanport_wwn.port) + "<br> "
                if k.Sanport_wwn:
                    rx += str(k.Sanport_wwn.rx) + "<br> "
                    tx += str(k.Sanport_wwn.tx) + "<br> "
                if k.host_wwn:
                    host += str(k.host_wwn) + "<br> "
                    hostapp += str(k.host_wwn.app) + "<br> "
            html += "<tr>" + \
                    "<td>" + str(i.id) +"</td>"+ \
                    "<td>" + str(i.hostname) +"</td>"  + \
                    "<td>" + hostgoupname +"</td>"  + \
                    "<td>" + wwn +"</td>"  + \
                    "<td>" + sanwwn +"</td>"  + \
                    "<td>" + rx +"</td>"  + \
                    "<td>" + tx +"</td>"  + \
                    "<td>" + host +"</td>"  + \
                    "<td>" + hostapp +"</td>"  + \
                    "</tr>"
        # html = ""
        # obj = models.STHOST.objects.values("id", "hostname", "sthostgroup__hostgroupname", "wwn__wwn",
        #                             "wwn__Sanport_wwn__san__ip", "wwn__Sanport_wwn__slot",
        #                             "wwn__Sanport_wwn__port", "wwn__Sanport_wwn__rx", "wwn__Sanport_wwn__tx",
        #                             "wwn__host_wwn__app", "wwn__host_wwn__ip").filter(storage_id=12)
        # for i in obj:
        #     html += "<tr>" + \
        #             "<td>" + str(i["id"]) +"</td>"+ \
        #             "<td>" + str(i["hostname"]) +"</td>"  + \
        #             "<td>" + str(i["sthostgroup__hostgroupname"]) +"</td>"  + \
        #             "<td>" + str(i["wwn__wwn"]) +"</td>"  + \
        #             "<td>" + str(i["wwn__Sanport__san"]) + str(i["wwn__Sanport_wwn__slot"])+ str(i["wwn__Sanport_wwn__port"])+"</td>"  + \
        #             "<td>" + str(i["wwn__Sanport_wwn__rx"]) +"</td>"  + \
        #             "<td>" + str(i["wwn__Sanport_wwn__tx"]) +"</td>"  + \
        #             "<td>" + str(i["wwn__host_wwn__ip"]) +"</td>"  + \
        #             "<td>" + str(i["wwn__host_wwn__app"]) +"</td>"  + \
        #             "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def storage_port_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        html = ""
        obj = models.STPORT.objects.filter(storage_id=id)
        for i in obj:
            hostgoupname = ""
            for k in i.stportgroup_set.all():
                hostgoupname += str(k.portgroupname)
            rx = ""
            tx = ""
            ip = ""
            if i.wwn.Sanport_wwn:
                rx = str(i.wwn.Sanport_wwn.rx)
                tx = str(i.wwn.Sanport_wwn.tx)
            if i.wwn.Sanport_wwn:
                ip =  str(i.wwn.Sanport_wwn.san) + " " + str(i.wwn.Sanport_wwn.slot)+ "-" + str(i.wwn.Sanport_wwn.port)
            html += "<tr>" + \
                    "<td>" + str(i.id) +"</td>"+ \
                    "<td>" + str(i.portname) +"</td>"+ \
                    "<td>" + str(i.wwn) +"</td>"+ \
                    "<td>" + hostgoupname +"</td>"+ \
                    "<td>" + rx + "</td>" + \
                    "<td>" + tx + "</td>" + \
                    "<td>" +ip + "</td>" + \
                    "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def storage_lun_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        html = ""
        obj = models.STLUN.objects.filter(storage_id = id)
        for i in obj:
            lungroupname = ""
            for z in i.stlungroup_set.all():
                lungroupname += str(z.lungroupname)
            html += "<tr>" + \
                    "<td>" + str(i.lid) +"</td>"+ \
                    "<td>" + str(i.lunpname) +"</td>"+ \
                    "<td>" + str(i.lunsize) +"</td>"+ \
                    "<td>" + lungroupname +"</td>"+ \
                    "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def storage_disk_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        html = ""
        obj = models.DISK.objects.filter(storage_id=id)
        for i in obj:
            html += "<tr>" + \
                    "<td>" + str(i.diskslot) +"</td>"+ \
                    "<td>" + str(i.status) +"</td>"+ \
                    "<td>" + str(i.disktype) +"</td>"+ \
                    "<td>" + str(i.diskstatus) +"</td>"+ \
                    "<td>" + str(i.disksize) +"</td>"+ \
                    "<td>" + str(i.datatype) +"</td>"+ \
                    "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def storage_raid_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        html = ""
        obj = models.RAIDgroup.objects.filter(storage_id=id)
        for i in obj:
            html += "<tr>" + \
                    "<td>" + str(i.rid) +"</td>"+ \
                    "<td>" + str(i.raidname) +"</td>"+ \
                    "<td>" + str(i.raidtype) +"</td>"+ \
                    "<td>" + str(i.raidsize) +"</td>"+ \
                    "<td>" + str(i.radifree) +"</td>"+ \
                    "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def storage_work_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        html = ""
        from work.models import Work
        obj = Work.objects.filter(WO_storage_id = id)
        for i in obj:
            html += "<tr>" + \
                    "<td>" + str(i.WO_time) +"</td>"+ \
                    "<td>" + str(i.WO_CAP) +"</td>"+ \
                    "<td>" + str(i.WO_CAPname) +"</td>"+ \
                    "<td>" + str(i.WO_text) +"</td>"+ \
                    "<td>" + str(i.WO_fishtime) +"</td>"+ \
                    "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))


def storage_stmap_rili_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        obj = models.STMAP.objects.filter(storage_id= id)
        html = ""
        for i in obj:
            # host = ""
            # for p in i.manyhost.all():
            #     host += str(p.hostname)
            # lungourpname = ""
            # for p in i.manylun.all():
            #     lungourpname += str(p.lunpname)
            html += "<tr>"+ \
                    "<td>" + str(i.id) +"</td>" + \
                     "<td>" + str(i.app)+"</td>" + \
                     "<td>" +str(i.Notes) +"</td>" + \
                     "<td>" +str(i.mapname) +"</td>" + \
                    "<td>" + str(i.totalcap) +"</td>" + \
                    "</tr>"
        ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def stroage_mess_host_rili_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        obj = models.STHOST.objects.filter(storage_id=id)
        html =""
        for i in obj:
            hostgoupname = ""
            for k in i.sthostgroup_set.all():
                hostgoupname += str(k.hostgroupname)
            wwn = ""
            sanwwn = ""
            rx = ""
            tx =""
            host = ""
            hostapp = ""
            for k in i.wwn_set.all():
                wwn += str(k.wwn) + "<br> "
                if k.Sanport_wwn:
                    sanwwn += str(k.Sanport_wwn.san) + " " + str(k.Sanport_wwn.slot) + "-" + str(k.Sanport_wwn.port) + "<br> "
                if k.Sanport_wwn:
                    rx += str(k.Sanport_wwn.rx) + "<br> "
                    tx += str(k.Sanport_wwn.tx) + "<br> "
                if k.host_wwn:
                    host += str(k.host_wwn) + "<br> "
                    hostapp += str(k.host_wwn.app) + "<br> "
            html += "<tr>" + \
                    "<td>" + str(i.id) +"</td>"+ \
                    "<td>" + str(i.hostname) +"</td>"  + \
                    "<td>" + str(i.Notes) +"</td>"  + \
                    "<td>" + wwn +"</td>"  + \
                    "<td>" + sanwwn +"</td>"  + \
                    "<td>" + rx +"</td>"  + \
                    "<td>" + tx +"</td>"  + \
                    "<td>" + host +"</td>"  + \
                    "<td>" + hostapp +"</td>"  + \
                    "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))
def storage_lun_rili_ajax(request):
    ret = {"status": True, "error": None, "data": None}
    if request.method == "POST":
        id = request.POST["id"]
        html = ""
        obj = models.STLUN.objects.filter(storage_id = id)
        for i in obj:
            lungroupname = ""
            for z in i.stmap_set.all():
                lungroupname += str(z.mapname)
            html += "<tr>" + \
                    "<td>" + str(i.lid) +"</td>"+ \
                    "<td>" + str(i.lunpname) +"</td>"+ \
                    "<td>" + str(i.lunsize) +"</td>"+ \
                    "<td>" + lungroupname +"</td>"+ \
                    "<td>" + str(i.Notes) +"</td>"+ \
                    "</tr>"
    ret = {"status": True, "error": None, "data": html}
    return HttpResponse(json.dumps(ret))